#pip install email, smtplib

import smtplib
import email.utils
from email.mime.text import MIMEText
import time, datetime
import glob
import os

monitor_dir='./output/ckpts/mate_output/tagging_20241216_110249'

def send_email():
    files = [f for i, f in enumerate(glob.iglob(monitor_dir + '/*', recursive=True))]
    log_file = os.path.join(monitor_dir, '_log_.log')
    
    log_content = open(log_file, 'r', encoding='utf-8').readlines()
    log_content = '\n'.join(log_content[-50:])
    files_str = '\n'.join(files) + '\n===============\n' + log_content
    
    message = MIMEText(f"{files_str}")
    message['To'] = email.utils.formataddr(('zhaoang909', 'zhaoang909@qq.com'))
    message['From'] = email.utils.formataddr(('from http://192.168.100.114:9999/', 'zhaoang909@qq.com'))
    message['Subject'] = '训练输出文件监控'
    server = smtplib.SMTP_SSL('smtp.qq.com', 465)
    server.login('zhaoang909@qq.com','sleeggfgryhybhhj')
    server.set_debuglevel(True)
    try:
        server.sendmail('zhaoang909@qq.com', ['zhaoang909@qq.com'],msg=message.as_string())
    finally:
        server.quit()

def send_loop():
    
    while True:
        now_hour =  datetime.datetime.now().hour
        if now_hour in [12, 18]:
            send_email()
        time.sleep(60*60)

if __name__ == '__main__':
    send_loop()